#coding = utf-8
import os,time,datetime,sched
import os.path
from django.http import HttpResponse as hr
from saveUsers.models import savedADDR
from django.template.loader import render_to_string as rts
from django.views.decorators.gzip import gzip_page
from threading import Timer

statno = 'FRC TEAM 6980'
dstr = "./src/diary/"

date,dirs,content,title,date,month,cdate,day,today,schedule = time.strftime('%Y.%m.%d'),[],{},{},{},{},{},{},{},sched.scheduler(time.time, time.sleep)

def refr_diary():
	i = 0
	for fil in os.listdir(dstr):
		if os.path.isdir(dstr+fil):
			if not fil in dirs:
				dirs.append(fil)
			else:
				continue
		for fi in os.listdir(dstr+fil):
			flag = False
			if ".txt" in fi:
				flag = True
				content[fil] = open(dstr+fil+"/"+fi).read()#.replace("@img=#", "\"<img src=\"" + dstr + fil + "/").replace("#@", "\">\"")
				dirs.append(fil)
				date[fil] = content[fil].split("\n")[0].split(":")[1]
				today[fil] = date[fil]
				ca = time.strptime(date[fil],'%Y/%m/%d')
				cy,cm,cd = ca[:3]
				c1 = datetime.datetime(cy,cm,cd)
				day[fil] = c1.strftime('%d')
				month[fil] = c1.strftime('%b')
				cdate[fil] = c1.strftime('%Y.%m.%d')
				title[fil] = content[fil].split("\n")[1].split(":")[1]
				content[fil] = content[fil].split("内容:")[1][1:]
				print(dirs)
				break
			if not flag:
				dirs.remove(fil)

def refr_index():
	pass

def recordIP(request):
	req,ip,ua = request.get_full_path(),request.META['REMOTE_ADDR'],request.META['HTTP_USER_AGENT']
	sAd,flg = savedADDR.objects.get_or_create(ip=ip)
	if flg:
		sAd.times = 1
		sAd.req = req
		sAd.ua = ua
		sAd.save()
	else:
		sAd.times = sAd.times + 1
		sAd.req = req
		sAd.ua = ua
		if sAd.times >= 1000 :
			sAd.dang = True
			return True
		sAd.save()
	return False

def reset_rec():
	savedADDR.objects.filter(dang=False).update(times=0)
	print("Saved Users Cleared")
	Timer(3600,reset_rec,()).start()
reset_rec()

@gzip_page
def index(resp):
	cont = {
		"tname": statno,
		"title": "首页",
	}
	return hr(rts("index.html",cont)) if not recordIP(resp) else p500(resp)

@gzip_page
def diary(resp):
	refr_diary()
	cont = {
		"tname": statno,
		"title": "开发日志",
		"cont": dirs,
		'day': day,
		'month': month,
		'date': date,
		'today': today,
		'title_js': title,
		'cdate': cdate,
		'content': content,
	}
	return hr(rts("diary.html",cont)) if not recordIP(resp) else p500(resp)

@gzip_page
def sponsors(resp):
	cont = {
		"tname": statno,
		"title": "赞助商们",
	}
	return hr(rts("sponsers.html",cont)) if not recordIP(resp) else p500(resp)

@gzip_page
def aboutus(resp):
	cont = {
		"tname": statno,
		"title": "关于我们",
	}
	return hr(rts("aboutus.html",cont)) if not recordIP(resp) else p500(resp)

@gzip_page
def p403(resp):
	cont = {
		"tname": statno,
		"title": "页面错误-403",
		"statno": 403,
		"statna": "Permisson Denied!"
	}
	return hr(rts("error.html",cont)) if not recordIP(resp) else p500(resp)

@gzip_page
def p404(resp):
	cont = {
		"tname": statno,
		"title": "页面错误-404",
		"statno": 404,
		"statna": "Page Not Found!"
	}
	return hr(rts("error.html",cont)) if not recordIP(resp) else p500(resp)

@gzip_page
def p500(resp):
	recordIP(resp)
	cont = {
		"tname": statno,
		"title": "页面错误-500",
		"statno": 500,
		"statna": "Server Internal Error!"
	}
	return hr(rts("error.html",cont))
